package com.hdoit.apollo.web.shop.providers;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.jsp.PageContext;

import com.tennetcn.core.common.message.ListItem;
import com.tennetcn.core.common.utils.CommonApplicationContextUtil;
import com.tennetcn.core.common.utils.PageContextUtils;
import com.tennetcn.core.plugins.devshorts.enumerable.Enumerable;
import com.tennetcn.web.component.attribute.provider.IMultipleOptionListProvider;
import com.tennetcn.authority.logical.model.Role;
import com.tennetcn.authority.logical.service.IRoleLoginUserService;
import com.tennetcn.authority.logical.service.IRoleService;
import com.tennetcn.authority.viewmodel.RoleSearch;

/** 
 * @author      tancongzhu
 * @email       851480680@qq.com
 * @createtime  2017年8月14日 下午5:00:02
 * @comment 
 */
public class StaffRoleProvider implements IMultipleOptionListProvider<ListItem>{
	private List<ListItem> dataList;
	@Override
	public List<ListItem> getDataList(Object viewData) {
		List<Role> roles= getRoles();
		if(roles==null||roles.size()<=0){
			return null;
		}
		dataList=new ArrayList<ListItem>();
		ListItem listItem=null;
		for (Role role : roles) {
			if("manager".equals(role.getRoleMark())||"salesperson".equals(role.getRoleMark())|| "stock".equals(role.getRoleMark())) {
				listItem=new ListItem();
				listItem.setText(role.getRoleName());
				listItem.setValue(role.getRoleId());
				
				dataList.add(listItem);
			}
			
		}
		return dataList;
	}
	
	@Override
	public List<ListItem> getSelectedItems(Object value, Object viewData) {
		PageContext pageContext=(PageContext)viewData;
		String id=PageContextUtils.getParam(pageContext, "id");
		
		List<String> roleIds=queryRoleIdsByLoginUserId(id);
		if(roleIds==null||roleIds.size()<=0){
			return null;
		}
		List<ListItem> selDataList=new ArrayList<ListItem>();
		for (String roleId : roleIds) {
			ListItem listItem=Enumerable.init(dataList).filter(data->roleId.equals(data.getValue())).first();
			if(listItem!=null){
				selDataList.add(listItem);
			}
		}
		return selDataList;
	}
	
	private List<Role> getRoles(){
		IRoleService roleService=CommonApplicationContextUtil.getCurrentContext().getBean(IRoleService.class);
		RoleSearch search=new RoleSearch();
		/*search.setBuId("de83f779-ecce-4725-a35b-750990833d7b");*/
		return roleService.queryList(search);
	}
	
	private List<String> queryRoleIdsByLoginUserId(String id){
		IRoleLoginUserService roleLoginUserService=CommonApplicationContextUtil.getCurrentContext().getBean(IRoleLoginUserService.class);
		return roleLoginUserService.queryRoleIdsByLoginUserId(id);
	}
}
